<template>
  <div :class="$style.page">
    <h1>使用Web Worker计算斐波那契数列，避免阻塞UI线程</h1>

    <el-input-number v-model="pageOpts.num" size="large" :max="50"></el-input-number>

    <el-button
      :class="$style.btn"
      type="primary"
      size="large"
      :loading="pageOpts.loading"
      @click="onComputed"
      >计算</el-button
    >

    <div :class="$style.result">
      <el-progress
        v-if="pageOpts.loading"
        :percentage="pageOpts.progress"
        :stroke-width="15"
        status="success"
        striped
        striped-flow
        :duration="100"
        :show-text="false"
      />

      <el-alert v-if="pageOpts.result < 0" center type="warning" :closable="false">
        <template #title>
          <span v-if="pageOpts.loading">计算中...</span>
          <span v-else>等待计算</span>
        </template>
      </el-alert>

      <el-alert v-else type="success" center :closable="false">
        <template #title>
          <p>结果：{{ pageOpts.result }}</p>
          <p>耗时：{{ pageOpts.time.toFixed(2) }}ms</p>
        </template>
      </el-alert>
    </div>
  </div>
</template>

<script lang="ts" setup>
const base = import.meta.env.VITE_BEFORE_STATIC_PATH
const worker = new Worker(`${base}/worker/map.js`)

const pageOpts = reactive({
  num: 10,
  time: 0,
  result: -1,
  loading: false,
  progress: 0
})

// 接收Worker的消息
worker.onmessage = e => {
  const data = e.data
  if (e.data.type === 'progress') {
    pageOpts.progress = data.progress
  } else {
    pageOpts.result = data.result
    pageOpts.time = data.time
    pageOpts.loading = false
  }
}

const reset = () => {
  pageOpts.time = 0
  pageOpts.result = -1
  pageOpts.progress = 0
}

const onComputed = () => {
  reset()
  pageOpts.loading = true
  // 向Worker发送消息
  worker.postMessage(pageOpts.num)
}
</script>

<style lang="scss" module>
@use './style.scss';
</style>
